<template>
  <div class="login-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>登录</span>
        </div>
      </template>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input v-model="loginForm.captcha"></el-input>
            </el-col>
            <el-col :span="8">
              <img @click="refreshCaptcha" alt="验证码"
                   style="cursor: pointer; width: 100%; height: 40px;">
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import {ref} from 'vue';
import {ElMessage} from 'element-plus';
import axios from '@/util/axios.js'
import {useRouter} from 'vue-router'
import {setToken} from "@/util/tokenUtil.js";
import {useMenuStore} from "@/stores/menu.js";
const router = useRouter();
const store = useMenuStore()
const loginFormRef = ref(null);
const loginForm = ref({
  username: 'admin',
  password: 'aaa111',
  captcha: '2020'
});
const captchaSrc = ref('/api/captcha'); // 假设验证码接口为 /api/captcha

const rules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ],
  captcha: [
    {required: true, message: '请输入验证码', trigger: 'blur'}
  ]
};

const refreshCaptcha = () => {
  // captchaSrc.value = `/api/captcha?t=${Date.now()}`;
};

const submitForm = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      axios.post('/user/login', loginForm.value)
          .then(res => {
            const responseData = res.data;
            if (responseData.code !== 0) {
              ElMessage(responseData.msg)
              return
            }
            ElMessage.success('登录成功');
            const token = responseData.info;
            setToken(token)

            // 路由跳转
            router.replace({path:"/index"})
          })

    } else {
      ElMessage.error('请输入正确的信息');
      return false;
    }
  });
}


</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.box-card {
  width: 400px;
}
</style>
